// pages/order/orderList/orderList.js
var ajax = require('../../../utils/httpUtil.js');
var dateCalu = require('../../../utils/dateUtils.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: null,
    pageNum: 1,
    orderStatus:null,
    isShow:0,
	payType:2, //1=微信 2=线下
	isClick:1, //1可以点击 0是不可以点击
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onLoad~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    var that = this;
    that.loadData(1,1);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if(that.data.isShow==1){
      console.log("onShow~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
      that.loadData(1, 1);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("onHide~~~~~~~~~~~~~~~~~~~~");
    var that = this;
    that.setData({
      isShow:1
    })
  },

  /**
   * 查看订单详情
   */
  getOrderDetails: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../order/orderDetails/orderDetails?id='+id
    })
  },

  /**
   * 评价
   */
  evaluateOrder: function (e) {
    var orderId = e.currentTarget.dataset.id;
    var shopTitle = e.currentTarget.dataset.shoptitle;
    wx.navigateTo({
      url: '../../order/evaluate/evaluate?orderId=' + orderId + "&shopTitle=" + shopTitle + "&typeUrl=" + 1
    })
  },

  /**
   * 删除订单
   */
  deleteOrder: function (e) {
    var that=this;
    var orderId = e.currentTarget.dataset.id;
    updateOrdersInfo(6, orderId, that,1);
  },

  /**
   * 取消订单
   */
  cancelOrder: function (e) {
    var that = this;
	console.log(e);
    var orderId = e.currentTarget.dataset.id;
	  var payType = e.currentTarget.dataset.paytype;
	console.log(payType);
	this.setData({
		payType:payType?payType:2
	})
    updateOrdersInfo(5, orderId, that,1);
  },

 

  /**
   * 联系商家
   */
  linkShop: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone, //此号码并非真实电话号码，仅用于测试
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    });
  },

  /**
   * 去支付
   */
  payOrder: function (e) {
    var orderId = e.currentTarget.dataset.id;
    console.log(orderId);

    ajax.reqPost('/xorder/payOrdersInfo', { id: orderId}, function (res) {
      console.log(res);
      wx.requestPayment({
        'timeStamp': res.returnObject.timestamp + '',
        'nonceStr': res.returnObject.noncestr + '',
        'package': res.returnObject.wxpackage + '',
        'signType': 'MD5',
        'paySign': res.returnObject.paySign + '',
        'success': function (res) { 
          console.log(res) 
        },'fail': function (res) {
          console.log(res);
          if (res === 'requestPayment:fail cancel') {
            console.log('用户取消支付,返回订单列表并刷新');
          }
        },'complete': function (res) { 
          console.log(res) 
        }
      })
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.loadData(1,1);
    setTimeout(() => {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 2000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    console.log(that.data);
    var pageNum = this.data.pageNum; // 获取当前页面 data 中的数据
    console.log(pageNum);
    that.loadData(0,pageNum+1);
  },

  /**
   * 加载订单列表数据
   * isClear 0加载更多 1刷新
   * pageNum 当前页数
   */
  loadData: function (isClear,pageNum) {
    console.log("请求数据isClear=" + isClear + "-pageNum=" + pageNum);
    var that = this;
    //res.data  'b8qp'
    
    // 获取用户id
    wx.getStorage({
      key: 'uid',
      success: function (res) {
		  console.log(res);
		//'b8qp'res.data
        ajax.reqPost('xorder/getOrdersList', { userId: res.data, pageNum: pageNum }, function (res) {
          console.log(res);
          if (res.resultCode == 1000) {
            var orderList = null;

            //处理没有数据的情况
            if (res.returnObject != null) {
              //加载更多
              if (!isClear) {
                if (res.returnObject.isLastPage) {//最后一页了
                  orderList = that.data.orderList;
                  wx.showToast({
                    title: "没有更多了",
                    icon: 'none',
                    duration: 1500
                  })
                } else {
                  orderList = that.data.orderList;
                  orderList = orderList.concat(res.returnObject.list);
                }
              } else {
                orderList = res.returnObject.list;
              }
            } else {
              //加载更多
              if (!isClear) {
                orderList = that.data.orderList;
                wx.showToast({
                  title: "没有更多了",
                  icon: 'loading',
                  duration: 1300
                })
              } else {
                orderList = null;
              }
            }

            that.setData({
              orderList,
              pageNum
            })
			  wx.hideNavigationBarLoading() //完成停止加载
			  wx.stopPullDownRefresh() //停止下拉刷新
            //调用定时器
            countDown(that.data.orderList, that);

          }
        });
      },fail:function(){
        console.log("用户id获取失败");
		  wx.showToast({
			  title: '请前往「我的」授权登录',
			  icon: 'none',
			  duration: 2000
		  });
        //去登陆处理
      }
    })

    
  }


})


/**
 * 修改订单状态
 * status 5=取消订单 6=删除订单
 * id 订单id
 * type 1页面操作   2定时器取消
 */
function updateOrdersInfo(status, id, that, type,i) {
 if(that.data.isClick == 1){
	that.setData({
		isClick:0,
	})
 }else{
	 return;
 }
  ajax.reqPost('xorder/updateOrdersInfo', { id: id, status: status }, function (res) {
    console.log(res);
    if (res.resultCode == 1000) {
      if (type==1){
		var ty =   that.data.payType;
        wx.showToast({
			title: status == 5 ? (ty == 1 ? ("取消成功，如有付款，付款金额将在5分钟内返还至微信零钱") :"取消成功" ): "删除成功",
		  icon: status == 5 ? "none" : "success",
          mask: true,
			duration: status == 5 ? 5000 : 2000
        })
		  that.setData({
			  isClick: 1
		  })
        //刷新页面
        that.loadData(1, 1);
      }else {
        //定时器过时取消订单,将状态改为已取消
        // that.setData({
        //   orderStatus:5
        // })
        console.log(i);
        console.log(that.data.orderList);
        that.data.orderList[i].status=5;
        that.setData({
          orderList: that.data.orderList
        })
        //that.data.orderList[{},{},{}]
      }
    }else if(res.resultCode == 1010 ){
		wx.showToast({
			title: res.returnObject,
			icon: 'none',
			duration: 1000
		})
	}
	that.setData({
		isClick:1
	})
  });
}
/**
 * 倒计时 
 */
function countDown(orderList, that) {
  //查询订单时判断待支付订单是否超时
  for (var i in orderList) {
    if (orderList[i].status == 1) {//待支付
      var dateMap = dateCalu.getTwoTime(orderList[i].createTime, dateCalu.formatDate(new Date()));
      console.log(dateMap);
      if (dateMap.m >= 15 || dateMap.h > 0 || dateMap.d > 0) {
        updateOrdersInfo(5, orderList[i].id, that, 2, i);//取消订单
      }
    }
  }


  //调用定时器
  console.log(orderList);

  // var count=0;
  // var downTimes=[];
  // for (var i in orderList){
  //   if (orderList[i].status == 1) {//待支付
  //     count++;
  //     downTimes.push(orderList[i]);
  //   }
  // }

  // //有待支付的订单
  // if(count>0){
  //   console.log("count=",count);
  //   console.log(downTimes);
  //   var interval = setInterval(function () {
  //     if (count > 0){
  //       console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~",downTimes);
  //       for (var j in downTimes) {
  //         if (downTimes[j].status == 1){
  //           var dateMap = dateCalu.getTwoTime(downTimes[j].createTime, dateCalu.formatDate(new Date()));
  //           console.log("j=" + j, dateMap);
  //           if (dateMap.m >= 1 && downTimes[j].status == 1) {//创建时间超过15分钟的，取消订单
  //             console.log("取消订单~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  //             updateOrdersInfo(5, downTimes[j].id, that, 2, j);//取消订单
  //             count--;
  //             console.log("count=" + count);
  //             downTimes[j].status = 5;
  //             console.log("downTimesStatus="+downTimes[j].status);
  //           }
  //         }
  //       }
  //     }else {
  //       console.log("停止定时器~~~~~~~~~~~~~~~~~~~~~");
  //       clearInterval(interval);
  //     }
  //   }, 1000)
  // }





  // interval[id] = setInterval(function () {
  //   console.log("interval[id]", interval[id]);
  //   //根据创建时间和当前时间计算时间差爱
  //   var dateMap = dateCalu.getTwoTime(createTime, dateCalu.formatDate(new Date()));
  //   console.log(dateMap);

  //   //时间差大于15分钟直接取消订单，小于15分钟页面展示倒计时时间
  //   if (dateMap.m >= 2) {
  //     console.log("大于15分钟取消订单~~~~~");
  //     //停止定时器
  //     console.log("interval=", interval[id]);
  //     clearInterval(interval[id]);
  //     //取消订单
  //     updateOrdersInfo(5, id, that, 2, i);
  //   } else {
  //     //页面展示倒计时
  //     console.log("页面展示倒计时~~~~~");
  //     var countDownTime1 = 14 - dateMap.m;
  //     var countDownTime2 = 60 - dateMap.s;

  //     var countDownTime = countDownTime1 + ":" + countDownTime2;
  //     console.log("倒计时时间=", countDownTime);
  //     var time = countDownTime.split(":");
  //     var minute = parseInt(time[0]);
  //     var second = parseInt(time[1]);

  //     if (minute == 0 && second == 0) {//倒计时结束，结束定时器
  //       //停止定时器
  //       console.log("that.data.interval=", that.data.interval);
  //       clearInterval(that.data.interval);
  //       //取消订单
  //       console.log("页面倒计时到时，取消订单~~~~~");
  //       updateOrdersInfo(5, id, that, 2, i);
  //     } else {
  //       if (second > 0) {
  //         second--;
  //       } else if (second == 0) {
  //         minute--;
  //         second = 59;
  //       }
  //     }
  //   }
  // }, 1000)
}